package cn.xinfei.xdecision.common.model.component.decisiontree;

import cn.xinfei.xdecision.common.model.component.IgnoredParamCheck;
import cn.xinfei.xdecision.common.utils.constant.SysConstant;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@SuppressWarnings("serial")
@TableName("t_decision_tree_detail")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DecisionTreeDetail extends Model<DecisionTreeDetail> {
    //决策树详情id
    @TableId(type = IdType.AUTO)
    @IgnoredParamCheck
    private Long id;
    //决策表id
    private Long versionId;
    //字段en
    private String fieldCode;
    //父节点id
    @IgnoredParamCheck
    private Long parentId;
    //逻辑关系，如（&&，||）
    private String logicalSymbol;
    //节点类型：1-普通节点，2-叶子节点
    private Integer nodeType;
    //叶子节点对应决策结果值
    @IgnoredParamCheck
    private String resultValue;
    //结果类型：1常量 2变量 3自定义
    private Integer valueType;

    //创建时间
    @IgnoredParamCheck
    private Date createdTime;

    //修改时间
    @IgnoredParamCheck
    private Date updatedTime;

    //决策树详情列表
    @TableField(exist = false)
    private List<DecisionTreeDetailCondition> conditionList;

    @TableField(exist = false)
    private List<DecisionTreeDetail> children;

    @IgnoredParamCheck
    @TableField(exist = false)
    private String insertTempId;//插入临时id

    @IgnoredParamCheck
    @TableField(exist = false)
    private String tempParentId;//插入临时父id

    public void checkDetail(Set<String> emptyFieldSet) {
        if (!CollectionUtils.isEmpty(this.children)) {
            this.children.forEach(x -> checkDetail(x, emptyFieldSet));
        }
    }

    public void checkDetail(DecisionTreeDetail decisionTreeDetail, Set<String> emptyFieldSet) {
        List<DecisionTreeDetail> childrenList = decisionTreeDetail.getChildren();
        //叶子节点的父id和决策结果值不能为空
        if (CollectionUtils.isEmpty(childrenList)) {
            if (Objects.equals(decisionTreeDetail.getParentId(), SysConstant.ZERO)) {
                emptyFieldSet.add("parentId");
            }
            if (StringUtils.isEmpty(decisionTreeDetail.getResultValue())) {
                emptyFieldSet.add("resultValue");
            }
        } else {
            childrenList.forEach(x -> checkDetail(x, emptyFieldSet));
        }
    }
}
